import http from './http';
import { requestWithRetry } from '../utils/retry';

// 定义分页数据类型
interface PaginationData<T> {
  list: T[]
  pagination: {
    page: number
    pageSize: number
    total: number
  }
}

// 客户管理API
export const customerAPI = {
  // 获取客户列表
  getCustomers: async (params: any) => {
    try {
      // 添加组织ID参数
      const appStore = (window as any).appStore
      if (appStore && appStore.currentOrganization) {
        params.organizationId = appStore.currentOrganization.id
      }
      
      // 使用重试机制获取客户列表
      const response: any = await requestWithRetry(
        () => http.get('/customers', { params }),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: {
          list: response.data?.list || [],
          pagination: response.data?.pagination || {
            page: 1,
            pageSize: 20,
            total: 0
          }
        }
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '获取客户列表失败'
      }
    }
  },

  // 获取客户详情
  getCustomer: async (id: string) => {
    try {
      // 使用重试机制获取客户详情
      const response = await requestWithRetry(
        () => http.get(`/customers/${id}`),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '获取客户详情失败'
      }
    }
  },

  // 创建客户
  createCustomer: async (data: any) => {
    try {
      // 添加组织ID
      const appStore = (window as any).appStore
      if (appStore && appStore.currentOrganization) {
        data.organizationId = appStore.currentOrganization.id
      }
      const result = await http.post('/customers', data)
      return {
        success: true,
        data: result
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '创建客户失败'
      }
    }
  },

  // 更新客户
  updateCustomer: async (id: string, data: any) => {
    try {
      const result = await http.put(`/customers/${id}`, data)
      return {
        success: true,
        data: result
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '更新客户失败'
      }
    }
  },

  // 删除客户
  deleteCustomer: async (id: string) => {
    try {
      const result = await http.delete(`/customers/${id}`)
      return {
        success: true,
        data: result
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '删除客户失败'
      }
    }
  },

  // 批量删除客户
  batchDeleteCustomers: async (ids: string[]) => {
    try {
      const result = await http.post('/customers/batch-delete', { ids })
      return {
        success: true,
        data: result
      }
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '批量删除客户失败'
      }
    }
  },

  // 导出客户
  exportCustomers: async () => {
    try {
      const response = await http.get('/customers/export', {
        responseType: 'blob'
      });
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '导出客户失败'
      };
    }
  },

  // 导入客户模板
  exportTemplate: async () => {
    try {
      const response = await http.get('/customers/export-template', {
        responseType: 'blob'
      });
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '导出客户模板失败'
      };
    }
  },

  // 导入客户
  importCustomers: async (formData: FormData) => {
    try {
      const response = await http.post('/customers/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      // 统一导入结果结构
      const result = response.data || response;
      return {
        success: true,
        data: {
          importedCount: result.importedCount || 0,
          errorCount: result.errorCount || 0,
          errors: result.errors || []
        }
      };
    } catch (error: any) {
      return {
        success: false,
        data: {
          importedCount: 0,
          errorCount: 0,
          errors: []
        },
        message: error.message || '导入客户失败'
      };
    }
  },

  // 获取客户统计信息
  getCustomerStats: async () => {
    try {
      // 使用重试机制获取客户统计信息
      const response = await requestWithRetry(
        () => http.get('/customers/stats'),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '获取客户统计信息失败'
      };
    }
  }
};

export default customerAPI;